package com.learn.springcloud.hystrixexplainindetailconsumer.exception.handle.service;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.springframework.web.client.RestTemplate;

import java.sql.SQLException;

/**
 * 继承方式捕获异常
 * @Time : 2018/8/3 16:50
 * @Version : 1.0
 */
public class UserExceptionCatchExtendsWay extends HystrixCommand<String> {

    private RestTemplate restTemplate;
    private String name;


    public UserExceptionCatchExtendsWay(HystrixCommandGroupKey group, RestTemplate restTemplate, String name) {
        super(group);
        this.restTemplate = restTemplate;
        this.name = name;
    }

    @Override
    protected String run() throws Exception {
        System.out.println("UserServiceException Running : " + name);
        String url = "http://hystrix-explain-in-detail-provider/request/command/say/hello?name={1}";
        if("aaa".equals(name)){
            throw new RuntimeException(name);
        }else if("bbbb".equals(name)){
            throw new SQLException(name);
        }
        return restTemplate.getForObject(url, String.class, name);
    }

    @Override
    protected String getFallback(){
        Throwable e = this.getExecutionException();
        if("aaa".equals(name)){
            return "运行时异常";
        }else if("bbb".equals(name)){
            return "检查异常";
        }else{
            return "error, " + name;
        }
    }
}
